package com.mytijian.openapi.adapter.alihalt.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.mytijian.openapi.adapter.alihalt.consts.AlihaltConsts;
import com.mytijian.openapi.adapter.alihalt.dao.McodeOrderRelDAO;
import com.mytijian.openapi.adapter.alihalt.listener.AlihaltOutEventListenService;
import com.mytijian.openapi.core.client.IOpenAPIClient;
import com.mytijian.openapi.core.client.result.BaseResult;
import com.mytijian.openapi.core.client.result.OrderInfo;
import com.mytijian.openapi.core.client.result.OrderListResult;
import com.mytijian.openapi.core.model.AppConfig;
import com.mytijian.openapi.core.service.OpenApiAppConfigService;

@Service
public class AlihaltOutEventListenServiceImpl implements AlihaltOutEventListenService {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private McodeOrderRelDAO mcodeOrderRelDAO;

	@Autowired
	private OpenApiAppConfigService openAPIService;
	
	@Autowired
	private IOpenAPIClient client;

	@Override
	public void onMcodeDestory(List<String> mcodes) {
		if (mcodes != null && !mcodes.isEmpty()) {
			mcodes.forEach(this::doOnDestory);
		}
	}

	private void doOnDestory(String mcode) {

		String orderNum = mcodeOrderRelDAO.getOrderNumByMcode(mcode);
		if (StringUtils.isEmpty(orderNum)) {
			log.info("电子码[{}]未与订单关联", mcode);
			return;
		}

		log.info("电子码[{}]关联订单[{}]。", mcode, orderNum);
		AppConfig config = openAPIService.getConfig(AlihaltConsts.AppName);
		OrderListResult orderListResult = client.getOrderStatus(config, orderNum);

		if (orderListResult == null || StringUtils.isNotEmpty(orderListResult.getErrCode())) {
			log.error("!!! [阿里对接](电子码失效事件监听) 电子码[{}]关联订单[{}]，查询失败open-api 返回: {}", mcode, orderNum,
					JSON.toJSONString(orderListResult));
			return;
		}

		List<OrderInfo> orderInfoList = orderListResult.getOrders();
		if (orderInfoList == null || orderInfoList.isEmpty()) {
			log.info("!!! [阿里对接](电子码失效事件监听) 电子码[{}]关联订单[{}]，订单不存在。", mcode, orderNum);
			return;
		}

		OrderInfo order = orderInfoList.get(0);

		switch (order.getOrderStatus()) {
		case "paid":
		case "success":
		case "unexamined":
			doRevoke(mcode, config, order);
			break;

		case "examined":
		case "finish":
			doNotify(mcode, order, "电子码被销毁(淘宝店铺发起的)，但是用户已经完成体检，需要人工介入处理。");
			break;
			
		default:
			log.info("[阿里对接][电子码失效事件监听] 天猫通知电子码[{}]失效，关联订单[{}], 订单状态[{}]。程序未进行处理，", mcode, orderNum, order.getOrderStatus());
			break;
		}
	}

	private void doNotify(String mcode, OrderInfo order, String message) {
		log.error("!!! [阿里对接错误] 电子码[{}]，{}  体检订单号[{}]。 体检人 openId:{}, 体检中心:{}, 体检日期:{}", mcode, message,
				order.getOrderNum(), order.getOpenId(), order.getHospitalName(), order.getExamDate());
	}

	private void doRevoke(String mcode, AppConfig config, OrderInfo order) {
		BaseResult revokeResult = client.revoke(config, order.getOrderNum());
		if (revokeResult != null && "T".equals(revokeResult.getSuccess())) {
			log.warn("!!! [阿里健康对接] 电子码[{}]被撤回，关联订单[{}]撤销成功，请知悉。", mcode, order.getOrderNum());
		} else {
			log.error("!!! [阿里健康对接] 电子码[{}]被撤回，关联订单[{}]撤销失败，需人工介入处理。体检人 openId:{}, 体检中心:{}, 体检日期:{}", mcode,
					order.getOrderNum(), order.getOpenId(), order.getHospitalName(), order.getExamDate());
		}
	}

}
